import React from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate, useNavigate, Outlet, useLocation } from 'react-router-dom';
import { Layout, Menu, Avatar, Button, message } from 'antd';
import {
  HomeOutlined,
  ShoppingOutlined,
  UserOutlined,
  AppstoreOutlined,
  UploadOutlined,
  LogoutOutlined,
  LoginOutlined,
  UserAddOutlined
} from '@ant-design/icons';
import Login from './pages/Login';
import Register from './pages/Register';
import Home from './pages/Home';
import Profile from './pages/Profile';
import Orders from './pages/Orders';
import UserManage from './pages/UserManage';
import UserOrders from './pages/UserOrders';
import ProductManage from './pages/ProductManage';
import ProfileUser from './pages/ProfileUser';
import HomeUser from './pages/HomeUser';
import { useUserStore } from './store/user';

const { Sider, Content } = Layout;

// 公共布局组件（未登录状态）
const PublicLayout: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <div style={{ height: 56, background: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'flex-end', padding: '0 24px', borderBottom: '1px solid #f0f0f0' }}>
        {location.pathname !== '/login' && (
          <Button type="link" icon={<LoginOutlined />} onClick={() => navigate('/login')} style={{ marginRight: 16 }}>
            登录
          </Button>
        )}
        {location.pathname !== '/register' && (
          <Button type="link" icon={<UserAddOutlined />} onClick={() => navigate('/register')}>
            注册
          </Button>
        )}
      </div>
      <Content style={{ minHeight: 'calc(100vh - 56px)', background: '#f5f5f5', padding: '24px' }}>
        <Outlet />
      </Content>
    </Layout>
  );
};

// 路由守卫组件
const PrivateRoute: React.FC<{ element: React.ReactElement; requireAdmin?: boolean }> = ({ 
  element, 
  requireAdmin = false 
}) => {
  const { token, isAdmin } = useUserStore();
  
  if (!token) {
    return <Navigate to="/login" replace />;
  }

  if (requireAdmin && !isAdmin) {
    message.error('需要管理员权限');
    return <Navigate to="/home" replace />;
  }

  return element;
};

// 布局组件，左侧导航，右侧内容
const MainLayout: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { userName, isAdmin, clearUserInfo } = useUserStore();

  const handleLogout = () => {
    clearUserInfo();
    navigate('/login');
  };

  // 基础菜单项
  const baseMenuItems = [
    {
      key: 'home',
      icon: <HomeOutlined />,
      label: '首页',
      onClick: () => navigate('/home')
    },
    {
      key: 'profile',
      icon: <UserOutlined />,
      label: '个人信息',
      onClick: () => navigate('/profile')
    }
  ];

  // 管理员菜单项
  const adminMenuItems = [
    {
      key: 'user-manage',
      icon: <UserOutlined />,
      label: '用户管理',
      onClick: () => navigate('/user-manage')
    },
    {
      key: 'product-manage',
      icon: <AppstoreOutlined />,
      label: '商品管理',
      onClick: () => navigate('/product-manage')
    }
  ];

  const userMenuItems = [
    ...baseMenuItems,
    {
      key: 'orders',
      icon: <ShoppingOutlined />,
      label: '我的订单',
      onClick: () => navigate('/orders')
    }
  ];

  const menuItems = isAdmin ? [...baseMenuItems, ...adminMenuItems] : userMenuItems;

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Sider width={180} style={{ background: '#fff' }}>
        <Menu 
          mode="inline" 
          selectedKeys={[location.pathname.split('/')[1] || 'home']} 
          style={{ height: '100%', borderRight: 0 }}
          items={menuItems}
        />
      </Sider>
      <Layout>
        <div style={{ height: 56, background: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'flex-end', padding: '0 24px', borderBottom: '1px solid #f0f0f0' }}>
          <span style={{ marginRight: 16 }}>欢迎，{userName}</span>
          {isAdmin && <span style={{ marginRight: 16, color: '#1890ff' }}>管理员</span>}
          <Button type="link" icon={<LogoutOutlined />} onClick={handleLogout}>退出</Button>
        </div>
        <Content style={{ minHeight: '100vh', background: '#f5f5f5', padding: '24px' }}>
          <Outlet />
        </Content>
      </Layout>
    </Layout>
  );
};

function App() {
  const { token, isAdmin } = useUserStore();

  return (
    <Router>
      <Routes>
        {/* 登录和注册页面完全独立，不使用任何布局 */}
        <Route path="/login" element={<Login />} />
        <Route path="/register" element={<Register />} />
        
        {token ? (
          // 已登录状态的路由
          <Route element={<MainLayout />}>
            <Route path="/home" element={<PrivateRoute element={isAdmin ? <Home /> : <HomeUser />} />} />
            <Route path="/profile" element={<PrivateRoute element={isAdmin ? <Profile /> : <ProfileUser />} />} />
            <Route path="/orders" element={<PrivateRoute element={<Orders />} />} />
            <Route path="/user-manage" element={<PrivateRoute element={<UserManage />} requireAdmin={true} />} />
            <Route path="/user-orders/:username" element={<PrivateRoute element={<UserOrders />} requireAdmin={true} />} />
            <Route path="/product-manage" element={<PrivateRoute element={<ProductManage />} requireAdmin={true} />} />
            <Route path="/" element={<Navigate to="/home" replace />} />
            <Route path="*" element={<Navigate to="/home" replace />} />
          </Route>
        ) : (
          // 未登录状态重定向到登录页
          <Route path="*" element={<Navigate to="/login" replace />} />
        )}
      </Routes>
    </Router>
  );
}

export default App;
